package com.forlove.app.qselect.friend.ui;

import android.Manifest;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.HandlerThread;
import android.os.Looper;
import android.os.Message;
import android.support.annotation.NonNull;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.AppCompatImageButton;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.forlove.app.R;
import com.forlove.app.common.base.ui.BaseFragment;
import com.forlove.app.common.utils.CipherUtils;
import com.forlove.app.common.utils.CryptAES;
import com.forlove.app.common.utils.LogUtil;
import com.forlove.app.common.utils.ParseHelper;
import com.forlove.app.common.utils.PermissionsChecker;
import com.forlove.app.common.utils.StringUtil;
import com.forlove.app.common.utils.StringUtils;
import com.forlove.app.common.widget.CircleImageView;
import com.forlove.app.common.widget.recyview.BaseRecyclerAdapter;
import com.forlove.app.event.ActiveFlagEvent;
import com.forlove.app.event.EventEntity;
import com.forlove.app.manager.EventManager;
import com.forlove.app.manager.FriendManager;
import com.forlove.app.manager.NetworkManager;
import com.forlove.app.manager.QRCodeManager;
import com.forlove.app.manager.UserManager;
import com.forlove.app.qselect.CommonEntity;
import com.forlove.app.qselect.MainActivity;
import com.forlove.app.qselect.answer.widght.InviteFriendDialog;
import com.forlove.app.qselect.friend.adapter.CommonSchoolAdapter;
import com.forlove.app.qselect.friend.adapter.FriendNewAskAdapter;
import com.forlove.app.qselect.friend.adapter.UnRegisterContactcsAdapter;
import com.forlove.app.qselect.friend.entity.ContactsFriendEntity;
import com.forlove.app.qselect.friend.entity.MineFriendEntity;
import com.forlove.app.qselect.friend.entity.MineFriendListEntity;
import com.forlove.app.qselect.friend.entity.NewsFriendsStatus;
import com.forlove.app.qselect.friend.entity.SearchFriendEntity;
import com.forlove.app.qselect.friend.presenter.MineNewFriendPresenter;
import com.forlove.app.qselect.friend.view.MineNewFriendView;
import com.forlove.app.qselect.index.ui.MineInfoActivity;
import com.forlove.app.qselect.login.entity.UserEntity;
import com.forlove.app.qselect.login.widget.ResetPwTipDialog;
import com.forlove.app.qselect.login.widget.SetGpsDialog;
import com.google.zxing.integration.android.IntentIntegrator;
import com.google.zxing.integration.android.IntentResult;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.OnClick;
import permissions.dispatcher.NeedsPermission;
import permissions.dispatcher.OnNeverAskAgain;
import permissions.dispatcher.OnPermissionDenied;
import permissions.dispatcher.RuntimePermissions;

/**
 * Created by yjl on 2017/10/19.
 */

@RuntimePermissions
public class MineNewFriendFragment extends BaseFragment<MineNewFriendPresenter>
        implements View.OnClickListener, MineNewFriendView, SwipeRefreshLayout.OnRefreshListener {

    public static boolean hasNewAdd = false; //有新的好友添加请求
    private final int load_cache = 40003; //加载缓存成功
    private final int load_contacts = 40004; //加载通讯录完成
    public static int add_new_school_friend = 40005;///添加新学校好友
    public static int add_new_contacts_friend = 40006;//添加通讯录注册好友
    public static int add_success = 1; //成功添加
    @BindView(R.id.mine_new_friend_toolbar)
    RelativeLayout mine_new_friend_toolbar;

    @BindView(R.id.image_mine)
    CircleImageView image_mine;

    @BindView(R.id.view_search_account)
    RelativeLayout view_search_account;

    @BindView(R.id.text_add_friends)
    TextView text_add_friends;    //添加

    @BindView(R.id.view_mine_friends)
    RelativeLayout view_mine_friends; //我的好友

    @BindView(R.id.view_new_friends_ask)
    LinearLayout view_new_friends_ask; //新的好友请求

    @BindView(R.id.view_new_friends)
    LinearLayout view_new_friends;//新的好友

    @BindView(R.id.view_contacts)
    LinearLayout view_contacts;// 添加手机联系人

    @BindView(R.id.list_new_ask)
    RecyclerView list_new_ask;  //新的好友请求

    @BindView(R.id.text_look_more_ask)
    TextView text_look_more_ask; //查看更多

    @BindView(R.id.list_recommend_friend)
    RecyclerView list_recommend_friend;//推荐的未添加好友

    @BindView(R.id.text_look_more_friends)
    TextView text_look_more_friends;  //学校好友更多

    @BindView(R.id.list_contacts)
    RecyclerView list_contacts;//通讯录好友

    @BindView(R.id.text_look_more_contacts)
    TextView text_look_more_contacts;//查看更多通讯录好友

    @BindView(R.id.refresh_new_friend)
    SwipeRefreshLayout refresh_new_friend;

    @BindView(R.id.view_has_new_friend)
    TextView view_has_new_friend;

    @BindView(R.id.bt_invite_friend)
    AppCompatImageButton bt_invite_friend;//邀请好友

    @BindView(R.id.bt_scan_qcode)
    AppCompatImageButton bt_scan_qcode;//扫一扫

    @BindView(R.id.bt_open_contacts)
    AppCompatImageButton bt_open_contacts;//打开通讯录

    private UserEntity userEntity;
    private List<MineFriendEntity> newAskFriends = new ArrayList<>();//新的好友添加请求
    private List<MineFriendEntity> recommendFriend = new ArrayList<>();//新的学校好友
    private List<MineFriendEntity> unRegisterFriend = new ArrayList<>();//本地于服务器合并后的未注册通讯录好友
    private FriendNewAskAdapter friendNewAskAdapter; //新的好友请求的
    private CommonSchoolAdapter friendRecommendAdapter; //学校好友的
    private UnRegisterContactcsAdapter unRegisterContactcsAdapter;//未注册通讯录好友
    private ResetPwTipDialog resetPwTipDialog;
    private Handler cacherHandler;
    private HandlerThread handlerThread;
    private Handler loadCoantactsHandler;
    private int commonSchoolNum = 0; //同校好友人数
    private int requestNum = 0; //好友请求人数
    private IntentIntegrator intentIntegrator;
    private SetGpsDialog showInfoDialog;
    private InviteFriendDialog inviteFriendDialog;

    @NeedsPermission(Manifest.permission.READ_CONTACTS)
    void needContacts() {
        //打开到通讯录
        startActivity(new Intent(mContext, AddContactsFriendActivity.class));
    }

    @OnNeverAskAgain(Manifest.permission.READ_CONTACTS)
    void neverAskContacts() {
        showTipDialog();
    }

    @OnPermissionDenied(Manifest.permission.READ_CONTACTS)
    void refuseContacts() {
        //拒绝
        Toast.makeText(mContext, getString(R.string.str_contacts_fail), Toast.LENGTH_SHORT).show();
    }

    private void showTipDialog() {
        if (showInfoDialog == null) {
            showInfoDialog = new SetGpsDialog(mContext);
            showInfoDialog.setTextMesseage(mContext.getString(R.string.str_contacts_tip));
            showInfoDialog.setTitleMsg(mContext.getString(R.string.str_contacts_title));
            showInfoDialog.setAgreeListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    PermissionsChecker.gotoPermissionSettings(mContext);
                    showInfoDialog.dismiss();
                }
            });
        }
        showInfoDialog.show();
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        MineNewFriendFragmentPermissionsDispatcher.onRequestPermissionsResult(this, requestCode, grantResults);
    }

    @Override
    public int getLayoutId() {
        return R.layout.fragment_new_mine_firends;
    }

    @Override
    protected void initFragmentView() {
        if (!isInit && MainActivity.getCurrentPosition() == MainActivity.POSITION_FRIEND) {
            initFragment();
            initData();
            isInit = true;
        }
    }

    private void initFragment() {
        refresh_new_friend.setOnRefreshListener(this);
        refresh_new_friend.setColorSchemeResources(R.color.common_green);
        image_mine.setOnClickListener(this);
        view_search_account.setOnClickListener(this);
        text_add_friends.setOnClickListener(this);
        text_look_more_contacts.setOnClickListener(this);
        text_look_more_friends.setOnClickListener(this);
        text_look_more_ask.setOnClickListener(this);
        view_mine_friends.setOnClickListener(this);
        bt_invite_friend.setOnClickListener(this);
    }

    @OnClick(R.id.bt_scan_qcode)
    public void openScanQcode() {
        //打开扫一扫
        if (intentIntegrator == null) {
            intentIntegrator = new IntentIntegrator(mContext);
        }
        intentIntegrator.setOrientationLocked(false)
                .setCaptureActivity(ScanQRCodeActivity.class) // 设置自定义的activity是CustomActivity
                .initiateScan(); // 初始化扫描
    }


    @OnClick(R.id.bt_open_contacts)
    public void openContacts() {
        MineNewFriendFragmentPermissionsDispatcher.needContactsWithPermissionCheck(this);
    }


    private void initData() {

        if (presenter == null) {
            presenter = new MineNewFriendPresenter(this);
        }
        if (userEntity == null) {
            userEntity = UserManager.getUesrInfo(mContext);
        }
        if (userEntity != null) {
            presenter.loadImageView(
                    mContext, image_mine, userEntity.mUserImage,
                    R.mipmap.image_mine_friend_avatar);
        }
        initHandler();
        initNewAskAdapter();
        initRecommendAdapter();
        initUnRegisterContactcsAdapter();
        loadFriendCache();
        presenter.loadFriendList();
    }

    private void initHandler() {
        if (cacherHandler == null) {
            cacherHandler = new Handler(Looper.getMainLooper(), new Handler.Callback() {
                @Override
                public boolean handleMessage(Message msg) {
                    switch (msg.what) {
                        case load_cache:
                            updateAskFriend();
                            //快速添加好友
                            updateFriendEasy();
                            //学校好友
                            updateRecommendFriend();
                            break;
                        case load_contacts:
//                            if (contactsInfoEntities.size() > 0) {
//                                updateFriendEasy();
//                            }
                            break;
                    }
                    return false;
                }
            });
        }
    }

    @Override
    public void onSelected(int pos) {
        if (MainActivity.getCurrentPosition() == MainActivity.POSITION_FRIEND) {
            LogUtil.e("yjl", "MineNewFriendFragment:" + pos);
            if (getView() == null && getActivity() != null) {
                mContext = getActivity();
                initFragment();
                initData();
            } else if (!isInit && getView() != null) {
                mContext = getActivity();
                //第一次进入
                initFragmentView();
            } else if (isInit && getView() != null) {
                //已经进入过了
                presenter.loadFriendList();
            }
        }

    }


    @Override
    public void onDestroy() {
        super.onDestroy();
        if (cacherHandler != null) {
            cacherHandler.removeCallbacksAndMessages(null);
            cacherHandler = null;
        }
        if (handlerThread != null) {
            handlerThread.quitSafely();
            handlerThread = null;
        }
        if (loadCoantactsHandler != null) {
            loadCoantactsHandler.removeCallbacksAndMessages(null);
            loadCoantactsHandler = null;
        }
        if (inviteFriendDialog != null) {
            inviteFriendDialog.dismiss();
            inviteFriendDialog.clearRecycle();
            inviteFriendDialog = null;
        }
        if (unRegisterContactcsAdapter != null) {
            unRegisterContactcsAdapter.clearData();
        }
    }

    private synchronized void loadFriendCache() {
        HandlerThread handlerThread = new HandlerThread("loadFriendCache");
        handlerThread.start();
        Handler loadHandler = new Handler(handlerThread.getLooper());
        loadHandler.post(new Runnable() {
            @Override
            public void run() {
                String mineFriend = FriendManager.getMineFriend(mContext);
                if (StringUtils.isNotEmpty(mineFriend)) {
                    MineFriendListEntity mineFriendListEntity =
                            ParseHelper.getModel(mineFriend, "data", MineFriendListEntity.class);
                    try {
                        requestNum = mineFriendListEntity.requestCount;
                        newAskFriends.clear();
                        newAskFriends.addAll(FriendManager.sortFriendRequest(mineFriendListEntity.friendsRequest));

                        unRegisterFriend.clear();
                        unRegisterFriend.addAll(mineFriendListEntity.concats);
                        unRegisterFriend.addAll(FriendManager.getCharmFriends(mineFriendListEntity.concats_unreg));

                        recommendFriend.clear();
                        recommendFriend.addAll(FriendManager.getCharmFriends(mineFriendListEntity.schoolFriends));
                        commonSchoolNum = mineFriendListEntity.schoolFcount;
                        cacherHandler.sendEmptyMessage(load_cache);
                    } catch (Exception e) {
                    }
                }
            }
        });
    }

    private void initNewAskAdapter() {
        if (friendNewAskAdapter == null) {
            friendNewAskAdapter = new FriendNewAskAdapter(getContext(),
                    R.layout.item_new_friends, newAskFriends, presenter, 3);
            list_new_ask.setAdapter(friendNewAskAdapter);
            LinearLayoutManager linearLayoutManager = new LinearLayoutManager(getContext());
            list_new_ask.setLayoutManager(linearLayoutManager);
            friendNewAskAdapter.hideEmptyView();
            friendNewAskAdapter.hideFooterView();
            friendNewAskAdapter.setOnItemClickListener(new BaseRecyclerAdapter.OnItemClickListener() {
                @Override
                public void onItemClick(View view, RecyclerView.ViewHolder holder, int position) {
                    //未添加
                    if (position < newAskFriends.size()) {
                        MineFriendEntity friendEntity = newAskFriends.get(position);
                        //添加好友，好友申请页面
                        if (friendEntity.status == NewsFriendsStatus.UNCONFIRM.getCode()
                                || friendEntity.status == NewsFriendsStatus.UNADDED.getCode()
                                || friendEntity.status == NewsFriendsStatus.WAITING.getCode()) {
                            SearchFriendEntity searchFriendEntity = new SearchFriendEntity();
                            searchFriendEntity.friendEntity = friendEntity;
                            searchFriendEntity.isFriend = false;
                            searchFriendEntity.note_times = friendEntity.charm;
                            Intent intent = new Intent(getContext(), SearchUserInfoActivity.class);
                            Bundle bundle = new Bundle();
                            bundle.putSerializable("friendinfo", searchFriendEntity);
                            bundle.putString("mobile", friendEntity.getAvaliableMobile());
                            intent.putExtras(bundle);
                            startActivity(intent);
                        } else if (friendEntity.status == NewsFriendsStatus.CONFIRMED.getCode()) {
                            Intent intent = new Intent(getContext(), MineInfoActivity.class);
                            Bundle bundle = new Bundle();
                            bundle.putString("mobile", friendEntity.mobile);
                            intent.putExtras(bundle);
                            startActivity(intent);
                        }
                    }
                }

                @Override
                public boolean onItemLongClick(View view, RecyclerView.ViewHolder holder, final int position) {
                    if (resetPwTipDialog == null) {
                        resetPwTipDialog = new ResetPwTipDialog(getContext());
                    }
                    resetPwTipDialog.setTextMesseage("确定删除该好友记录么？");
                    resetPwTipDialog.setAgreeListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            if (position < newAskFriends.size()) {
                                MineFriendEntity friendEntity = newAskFriends.get(position);
                                requestDeleteFriendRecord(friendEntity.mobile);
                            }
                            resetPwTipDialog.dismiss();
                        }
                    });
                    resetPwTipDialog.show();
                    return false;
                }
            });
        }
    }

    private void initRecommendAdapter() {
        if (friendRecommendAdapter == null) {
            friendRecommendAdapter = new CommonSchoolAdapter(getContext(),
                    R.layout.item_school_friends, recommendFriend, presenter, 3);
            list_recommend_friend.setAdapter(friendRecommendAdapter);
            LinearLayoutManager linearLayoutManager = new LinearLayoutManager(getContext());
            list_recommend_friend.setLayoutManager(linearLayoutManager);
            friendRecommendAdapter.hideEmptyView();
            friendRecommendAdapter.hideFooterView();
            friendRecommendAdapter.setOnItemClickListener(new BaseRecyclerAdapter.OnItemClickListener() {
                @Override
                public void onItemClick(View view, RecyclerView.ViewHolder holder, int position) {
                    //未添加
                    if (position < recommendFriend.size()) {
                        MineFriendEntity friendEntity = recommendFriend.get(position);
                        //添加好友，好友申请页面
                        if (friendEntity.status == NewsFriendsStatus.UNCONFIRM.getCode()
                                || friendEntity.status == NewsFriendsStatus.UNADDED.getCode()
                                || friendEntity.status == NewsFriendsStatus.WAITING.getCode()) {
                            SearchFriendEntity searchFriendEntity = new SearchFriendEntity();
                            searchFriendEntity.friendEntity = friendEntity;
                            searchFriendEntity.isFriend = false;
                            searchFriendEntity.note_times = friendEntity.charm;
                            Intent intent = new Intent(mContext, SearchUserInfoActivity.class);
                            Bundle bundle = new Bundle();
                            bundle.putInt("position", position);
                            bundle.putSerializable("friendinfo", searchFriendEntity);
                            bundle.putString("mobile", friendEntity.getAvaliableMobile());
                            intent.putExtras(bundle);
                            if (mContext instanceof Activity) {
                                ((Activity) mContext).startActivityForResult(intent, add_new_school_friend);
                            } else {
                                mContext.startActivity(intent);
                            }
                        } else if (friendEntity.status == NewsFriendsStatus.CONFIRMED.getCode()) {
                            Intent intent = new Intent(getContext(), MineInfoActivity.class);
                            Bundle bundle = new Bundle();
                            bundle.putString("mobile", friendEntity.mobile);
                            intent.putExtras(bundle);
                            startActivity(intent);
                        }
                    }
                }

                @Override
                public boolean onItemLongClick(View view, RecyclerView.ViewHolder holder, final int position) {
                    if (resetPwTipDialog == null) {
                        resetPwTipDialog = new ResetPwTipDialog(getContext());
                    }
                    resetPwTipDialog.setTextMesseage("确定删除该好友记录么？");
                    resetPwTipDialog.setAgreeListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            if (position < recommendFriend.size()) {
                                MineFriendEntity friendEntity = recommendFriend.get(position);
                                requestDeleteFriendRecord(friendEntity.mobile);
                            }
                            resetPwTipDialog.dismiss();
                        }
                    });
                    resetPwTipDialog.show();
                    return false;
                }
            });
        }
    }

    private void initUnRegisterContactcsAdapter() {
        if (unRegisterContactcsAdapter == null) {
            unRegisterContactcsAdapter = new UnRegisterContactcsAdapter(getContext(),
                    R.layout.item_friends_contacts, unRegisterFriend, presenter);
            list_contacts.setAdapter(unRegisterContactcsAdapter);
            LinearLayoutManager linearLayoutManager = new LinearLayoutManager(getContext());
            list_contacts.setLayoutManager(linearLayoutManager);
            unRegisterContactcsAdapter.hideEmptyView();
            unRegisterContactcsAdapter.hideFooterView();
            unRegisterContactcsAdapter.setOnItemClickListener(new BaseRecyclerAdapter.OnItemClickListener() {
                @Override
                public void onItemClick(View view, RecyclerView.ViewHolder holder, int position) {
                    if (position < unRegisterFriend.size()) {
                        MineFriendEntity friendEntity = unRegisterFriend.get(position);
                        //添加好友，好友申请页面
                        if ((StringUtils.isNotEmpty(friendEntity.username)
                                || StringUtils.isNotEmpty(friendEntity.realname))
                                && (friendEntity.status == NewsFriendsStatus.UNCONFIRM.getCode()
                                || friendEntity.status == NewsFriendsStatus.UNADDED.getCode()
                                || friendEntity.status == NewsFriendsStatus.WAITING.getCode())) {
                            SearchFriendEntity searchFriendEntity = new SearchFriendEntity();
                            searchFriendEntity.friendEntity = friendEntity;
                            searchFriendEntity.note_times = friendEntity.charm;
                            searchFriendEntity.isFriend = false;
                            Intent intent = new Intent(mContext, SearchUserInfoActivity.class);
                            Bundle bundle = new Bundle();
                            bundle.putInt("position", position);
                            bundle.putSerializable("friendinfo", searchFriendEntity);
                            bundle.putString("mobile", friendEntity.getAvaliableMobile());
                            intent.putExtras(bundle);
                            if (mContext instanceof Activity) {
                                ((Activity) mContext).startActivityForResult(intent, add_new_contacts_friend);
                            } else {
                                mContext.startActivity(intent);
                            }
                        } else if (friendEntity.status == NewsFriendsStatus.CONFIRMED.getCode()) {
                            Intent intent = new Intent(getContext(), MineInfoActivity.class);
                            Bundle bundle = new Bundle();
                            bundle.putString("mobile", friendEntity.mobile);
                            intent.putExtras(bundle);
                            startActivity(intent);
                        }
                    }
                }

                @Override
                public boolean onItemLongClick(View view, RecyclerView.ViewHolder holder, int position) {
                    return false;
                }
            });
        }
    }

    private void updateAskFriend() {
        if (friendNewAskAdapter == null) {
            return;
        }
        friendNewAskAdapter.updateDatas(newAskFriends);
        if (newAskFriends.size() == 0) {
            view_new_friends_ask.setVisibility(View.GONE);
        } else {
            view_new_friends_ask.setVisibility(View.VISIBLE);
            if (newAskFriends.size() > 3 || requestNum > 3) {
                text_look_more_ask.setVisibility(View.VISIBLE);
                text_look_more_ask.setText(String.format(getString(R.string.str_look_more), requestNum));
            } else {
                text_look_more_ask.setVisibility(View.GONE);
            }
        }
    }

    private void updateRecommendFriend() {
        if (friendRecommendAdapter == null) {
            return;
        }
        friendRecommendAdapter.updateDatas(recommendFriend);
        if (recommendFriend.size() == 0) {
            view_new_friends.setVisibility(View.GONE);
        } else {
            view_new_friends.setVisibility(View.VISIBLE);
            if (recommendFriend.size() > 3 || commonSchoolNum > 3) {
                text_look_more_friends.setVisibility(View.VISIBLE);
                text_look_more_friends.setText(String.format(getString(R.string.str_look_more), commonSchoolNum));
            } else {
                text_look_more_friends.setVisibility(View.GONE);
            }
        }
    }

    /**
     * 快速添加好友
     */
    private void updateFriendEasy() {
        if (unRegisterContactcsAdapter != null) {
            unRegisterContactcsAdapter.updateDatas(unRegisterFriend);
        }
        if (unRegisterFriend.size() == 0) {
            view_contacts.setVisibility(View.GONE);
        } else {
            view_contacts.setVisibility(View.VISIBLE);
            if (unRegisterFriend.size() < 30) {
                text_look_more_contacts.setVisibility(View.GONE);
            } else {
                text_look_more_contacts.setVisibility(View.VISIBLE);
//                text_look_more_contacts.setText(String.format(getString(R.string.str_look_more), unRegisterFriend.size()));
            }
        }

    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.image_mine:
                startActivity(new Intent(mContext, MineInfoActivity.class));
                break;
            case R.id.view_search_account:
                startActivity(new Intent(mContext, SearchFriendActivity.class));
                break;
            case R.id.text_add_friends:
                startActivity(new Intent(mContext, AddNewFriendActivity.class));
                break;
            case R.id.text_look_more_contacts:
                startActivity(new Intent(mContext, AddContactsFriendActivity.class));
                break;
            case R.id.text_look_more_friends:
//                startActivity(new Intent(mContext, NewFriendActivity.class));
                //查看更多学校好友
                startActivity(new Intent(mContext, SchoolFriendActivity.class));
                break;
            case R.id.text_look_more_ask:
                //好友请求页
//                startActivity(new Intent(mContext, FriendAskActivity.class));
                startActivityForResult(new Intent(mContext, FriendAskActivity.class), 1000);
                break;
            case R.id.view_school_friends:
                startActivity(new Intent(mContext, SchoolFriendActivity.class));
                break;
            case R.id.bt_invite_friend:
                //邀请好友
//                String commonUrl = ServerManager.getServerUrl() + "/invtepage?username=" + userEntity.userName;
                if (inviteFriendDialog == null) {
                    inviteFriendDialog = new InviteFriendDialog(getContext(), null, null, null);
                }
                inviteFriendDialog.show();
                break;
            case R.id.view_mine_friends:
                view_has_new_friend.setVisibility(View.GONE);
                startActivity(new Intent(mContext, MineFriendActivity.class));
                break;
        }
    }

    private void requestSearchFriend(String mobile) {
        if (TextUtils.isEmpty(mobile) || !StringUtil.isPhone(mobile)) {
            Toast.makeText(mContext, "没有找到该好友!", Toast.LENGTH_SHORT).show();
            return;
        }
        Map param = new HashMap();
        param.put("mobile", mobile);
        presenter.loadSearchFriend(param);
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        IntentResult intentResult = IntentIntegrator.parseActivityResult(requestCode, resultCode, data);
        if (intentResult != null && requestCode == IntentIntegrator.REQUEST_CODE) {
            if (intentResult.getContents() != null) {
                String ScanResult = intentResult.getContents();
                LogUtil.e("yjl", "扫描结果:" + ScanResult);
                String mobile = "";
                if (StringUtils.isMobile(ScanResult)) {
                    mobile = ScanResult;
                } else {
                    String keyStr = CipherUtils.md5(QRCodeManager.scan_key);
                    String decStr = CryptAES.AES_Decrypt(keyStr, ScanResult);
                    if (StringUtils.isMobile(decStr)) {
                        mobile = decStr;
                        LogUtil.e("yjl", "解密扫描结果:" + decStr);
                    }
                }
                if (StringUtils.isNotEmpty(mobile)) {
                    requestSearchFriend(mobile);
                } else {
                    Toast.makeText(mContext, "扫描失败!", Toast.LENGTH_LONG).show();
                }

            }
        } else {
            super.onActivityResult(requestCode, resultCode, data);
            if (requestCode == 1000) {
                if (resultCode == 1) {
                    int pos = data.getIntExtra("pos", -1);
                    //TODO 删除了某条记录
                    LogUtil.e("yjl", "删除请求:" + pos);
                }
            } else if (requestCode == add_new_school_friend && resultCode == add_success) {
                int pos = data.getIntExtra("position", -1);
                recommendFriend.get(pos).status = add_new_school_friend;
                friendRecommendAdapter.notifyItemChanged(pos);

            } else if (requestCode == add_new_contacts_friend && resultCode == add_success) {
                int pos = data.getIntExtra("position", -1);
                unRegisterFriend.get(pos).status = add_new_contacts_friend;
                unRegisterContactcsAdapter.notifyItemChanged(pos);
            }
        }
    }

    private void requestDeleteFriendRecord(String mobile) {
        Map param = new HashMap();
        param.put("mobile", mobile);
        presenter.loadDeleteFriendRecord(param);
    }

    @Override
    public void onEvent(EventEntity event) {
        if (event != null && event.eventId == EventManager.EVENT_NEW_FLAG) {
            //有新的好友动态
            if (event instanceof ActiveFlagEvent) {
                long oldAddtime = FriendManager.getNewFriendAddTime(getContext());
                if (event instanceof ActiveFlagEvent) {
                    ActiveFlagEvent activeFlagEvent = (ActiveFlagEvent) event;
                    if (activeFlagEvent.newFAddtime > oldAddtime) {
                        hasNewAdd = true;
                    } else {
                        hasNewAdd = false;
                    }
                }
            }
        } else if (event != null && event.eventId == EventManager.EVENT_UPDATE_USERINFO) {
            userEntity = UserManager.getUesrInfo(getContext());
            if (userEntity != null) {
                if (presenter != null && image_mine != null) {
                    presenter.loadImageView(
                            mContext, image_mine, userEntity.mUserImage,
                            R.mipmap.image_mine_friend_avatar);
                }
//                if (userEntity.scholar >= 10100 && userEntity.scholar <= 10109) {
//                    if (presenter != null) {
//                        presenter.loadFriendList();
//                    }
//                }
            }
        } else if (event != null && event.eventId == EventManager.EVENT_MINE_CONTACTS
                || event.eventId == EventManager.EVENT_ADD_NEW_FRIEND) {
            if (presenter != null) {
                presenter.loadFriendList();
            }
        }

    }


    @Override
    public void onRefresh() {
        presenter.loadFriendList();
        if (cacherHandler != null) {
            cacherHandler.postDelayed(new Runnable() {
                @Override
                public void run() {
                    refresh_new_friend.setRefreshing(false);
                }
            }, 6000);
        }
    }

    @Override
    public void updateContactsFriendView(ContactsFriendEntity contactsFriend) {
        //服务器返回通讯录好友
        refresh_new_friend.setRefreshing(false);
    }

    @Override
    public void showAgreeFriend(NetworkManager.ResultCode resultCode, String msg) {
        Toast.makeText(getContext(), msg, Toast.LENGTH_SHORT).show();
        if (resultCode.equals(NetworkManager.ResultCode.RESULT_SUCCESS)) {
            //添加好友成功
            view_has_new_friend.setVisibility(View.VISIBLE);
            presenter.loadFriendList();
        }
    }

    @Override
    public void showDeleteRecordView(CommonEntity commonEntity) {
        //删除添加好友信息
        presenter.loadFriendList();
    }

    @Override
    public void showErrorData(NetworkManager.ResultCode resultCode, String msg) {
        super.showErrorData(resultCode, msg);
        refresh_new_friend.setRefreshing(false);
    }

    @Override
    public void updateFriendListView(MineFriendListEntity mineFriendListEntity) {
        refresh_new_friend.setRefreshing(false);
        //好友信息接口
        requestNum = mineFriendListEntity.requestCount;
        newAskFriends.clear();
        newAskFriends.addAll(FriendManager.sortFriendRequest(mineFriendListEntity.friendsRequest));
        updateAskFriend();

        unRegisterFriend.clear();
        unRegisterFriend.addAll(mineFriendListEntity.concats);
        unRegisterFriend.addAll(FriendManager.getCharmFriends(mineFriendListEntity.concats_unreg));
        updateFriendEasy();

        recommendFriend.clear();
        recommendFriend.addAll(FriendManager.getCharmFriends(mineFriendListEntity.schoolFriends));
        commonSchoolNum = mineFriendListEntity.schoolFcount;
        updateRecommendFriend();
    }

    @Override
    public void showScanViewData(SearchFriendEntity searchFriendEntity) {
        if (searchFriendEntity != null && !searchFriendEntity.isFriend) {
            Intent intent = new Intent(mContext, SearchUserInfoActivity.class);
            Bundle bundle = new Bundle();
            bundle.putSerializable("friendinfo", searchFriendEntity);
            intent.putExtras(bundle);
            startActivity(intent);
        } else {
            //TODO 跳转好友详情页
            Toast.makeText(mContext, "此人已经是好友了", Toast.LENGTH_SHORT).show();
            Intent intent = new Intent(mContext, MineInfoActivity.class);
            Bundle bundle = new Bundle();
            bundle.putString("mobile", searchFriendEntity.friendEntity.mobile);
            intent.putExtras(bundle);
            startActivity(intent);

        }

    }


}